package com;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns="/asynservlet" ,asyncSupported =true)
public class AsynServlet extends HttpServlet {

	public AsynServlet() {
		super();
	}

	public void destroy() {
		super.destroy(); 
		
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		long startTime = System.currentTimeMillis(); 
        System.out.println("AsyncLongRunningServlet Start::Name=" 
                + Thread.currentThread().getName() + "::ID=" 
                + Thread.currentThread().getId()); 
 
        request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true); 
 
        int secs = Integer.valueOf(8000); 
        // 如果超过10秒则设置为10秒 
        if (secs > 10000) 
            secs = 10000; 
 
        AsyncContext asyncCtx = request.startAsync(); 
        asyncCtx.setTimeout(8000); 
        new Thread(new Excutor(asyncCtx)).start();
        long endTime = System.currentTimeMillis(); 
        System.out.println("AsyncLongRunningServlet End::Name=" 
                + Thread.currentThread().getName() + "::ID=" 
                + Thread.currentThread().getId() + "::Time Taken=" 
                + (endTime - startTime) + " ms."); 
	
	}
	
	

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}

	public void init() throws ServletException {
		// Put your code here
	}
	
	public class Excutor implements Runnable{
		
		private AsyncContext ctx = null;
		
		public Excutor(AsyncContext ctx){
			this.ctx = ctx;
		}

		@Override
		public void run() {
			
			try {
				System.out.println("start thread ....");
				 longProcessing(8000); 
			        try { 
			            PrintWriter out = ctx.getResponse().getWriter(); 
			            out.write("Processing done for " + System.currentTimeMillis() + " milliseconds!!"); 
			            //ctx.dispatch("/data.jsp");
			        } catch (IOException e) { 
			            e.printStackTrace(); 
			        } 
			        //完成异步线程处理 
			        //ctx.complete(); 
			     System.out.println("stop thread ....");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		private void longProcessing(int secs) { 
	        // 休眠指定的时间 
	        try { 
	            Thread.sleep(secs); 
	            
	        } catch (InterruptedException e) { 
	            e.printStackTrace(); 
	        } 
	    } 
		
	}

}
